package userService

import (
	userDto "news_for_deepseek_interface/dto/admin/system/user"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"
)

func List(params userDto.ListRequest) (*userDto.ListResponse, error) {
	db := model.GetInstance().GetDB().Model(&adminModel.AdminStruct{}).Debug()

	// id查询
	if params.Id != nil {
		db = db.Where("id = ?", *params.Id)
	}

	// 装修公司id查询
	if params.AdminSearchId != nil {
		db = db.Where("admin_id = ?", *params.AdminSearchId)
	}

	if params.AdminId != nil {
		db = db.Where("admin_id = ?", *params.AdminId)
	}

	// 装修公司手机号查询
	if params.AdminMobile != nil {
		var adminIds []int
		var admin adminModel.AdminStruct
		adminIds = admin.GetAdminByMobile(*params.AdminMobile)
		db = db.Where("admin_id in (?)", adminIds)
	}

	// 装修公司手机号查询
	if params.AdminMobile != nil {
		var adminIds []int
		var admin adminModel.AdminStruct
		adminIds = admin.GetAdminByMobile(*params.AdminMobile)
		db = db.Where("admin_id in (?)", adminIds)
	}

	// 手机号查询
	if params.Mobile != nil {
		db = db.Where("mobile like ?", "%"+*params.Mobile+"%")
	}

	//状态查询
	if params.Status != nil {
		db = db.Where("status = ?", *params.Status)
	}

	// 到期时间查询
	if params.Expires != nil {
		db = db.Where("expires between ? and ?", (*params.Expires)[0], (*params.Expires)[1])
	}

	// 地区查询
	if params.Region != nil {
		if len(*params.Region) == 3 {
			db = db.Where("province = ? and city = ? and area = ?", (*params.Region)[0], (*params.Region)[1], (*params.Region)[2])
		} else if len(*params.Region) == 2 {
			db = db.Where("province = ? and city = ?", (*params.Region)[0], (*params.Region)[1])
		} else if len(*params.Region) == 1 {
			db = db.Where("province = ?", (*params.Region)[0])
		}
	}

	// 地址查询
	if params.Address != nil {
		db = db.Where("address like ?", "%"+*params.Address+"%")
	}

	// 获取总数
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, err
	}

	// 获取数据列表
	var users []adminModel.AdminStruct
	if err := db.Offset((params.Page - 1) * params.Limit).
		Limit(params.Limit).
		Find(&users).Error; err != nil {
		return nil, err
	}

	// 构建响应
	response := &userDto.ListResponse{
		List:  make([]userDto.UserInfo, 0),
		Total: total,
		Limit: params.Limit,
		Page:  params.Page,
	}

	for _, user := range users {
		response.List = append(response.List, userDto.UserInfo{
			Id:       user.Id,
			Username: user.Username,
			Status:   user.Status,
			Expires:  user.Expires.Format("2006-01-02 15:04:05"),
			Region:   []string{user.Province, user.City, user.Area},
			Address:  user.Address,
			Mobile:   user.Mobile,
		})
	}

	return response, nil
}
